namespace Digitalmes.Application.Mes;

/// <summary>
/// 设备点检单表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class EquipCheckDocService : IDynamicWebApiService
{
    private readonly SugarRepository<EquipCheckDoc> _thisRepository;
    private readonly SugarRepository<EquipCheckTemplate> _templateRepo;
    private readonly SugarRepository<EquipCheckSubject> _subjectRepo;

    public EquipCheckDocService(SugarRepository<EquipCheckDoc> thisRepository, 
        SugarRepository<EquipCheckTemplate> templateRepo,
        SugarRepository<EquipCheckSubject> subjectRepo)
    {
        _thisRepository = thisRepository;
        _templateRepo = templateRepo;
        _subjectRepo = subjectRepo;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<EquipCheckDocDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(param.Key), s => s.Doc.Contains(param.Key))
            .OrderByDescending(s => s.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<EquipCheckDocDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<EquipCheckDocDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(s => s.Items)
            .FirstAsync(s => s.Id == id);
        return model.Adapt<EquipCheckDocDto>();
    }

    /// <summary>
    /// 添加点检单据
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(EquipCheckDocDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.Doc == model.Doc))
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        var doc = model.Adapt<EquipCheckDoc>();
        var template = await _templateRepo.GetFirstAsync(s => s.EquipId == doc.EquipId);
        if (template is null)
        {
            Oops.ThrowBah(ErrCode.E4009);
        }

        doc.Status = 1;
        doc.EquipCode = template!.EquipCode;
        doc.EquipName = template.EquipName;

        var subjects = await _subjectRepo.GetListAsync(s => template.SubjectCodes.Contains(s.SubjectCode));
        if (!subjects.Any())
        {
            Oops.ThrowBah(ErrCode.E4004);
        }

        foreach (var subject in subjects)
        {
            doc.Items!.Add(new EquipCheckDocLine
            {
                SubjectCode = subject.SubjectCode,
                SubjectName = subject.SubjectName,
                Content = subject.Content,
                Standard = subject.Standard,
                Result = "",
                Remark = "",
            });
        }

        // 导航更新
        return await _thisRepository.Context.InsertNav(doc)
            .Include(s => s.Items)
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 点检完成
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<bool> CompleteAsync(EquipCheckDocDto model)
    {
        var doc = await _thisRepository.GetByIdAsync(model.Id);
        doc.Complete();
        return await _thisRepository.UpdateAsync(doc);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public Task<bool> ModifyAsync(EquipCheckDocDto model)
    {
        Oops.ThrowBah(ErrCode.E4404);

        return Task.FromResult(true);
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids) =>
        await _thisRepository.DeleteAsync(m => ids.Contains(m.Id));
}
